<template>
  <div class="search">
    <van-nav-bar title="商品搜索" left-arrow @click-left="router.back()"/>

    <van-search v-model="searchValue" show-action placeholder="请输入搜索关键词" clearable background="#fff">
      <template #action>
        <div @click="goSearch(searchValue)">搜索</div>
      </template>
    </van-search>

    <div class="search-history" v-if="historyList.length > 0">
      <div class="title">
        <span>搜索历史</span>
        <van-icon name="delete" @click="clearHistory"/>
      </div>
      <div class="history-list">
        <div v-for="item in historyList" :key="item" class="history-item" @click="goSearch(item)">{{ item }}</div>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { ref } from 'vue'
import { useHistoryStore } from '@/stores/history'
import { storeToRefs } from 'pinia'
// 点击搜索 没有相同加到最前面
// 已有搜索 将原来的删除在加到最前面
// 清空历史
const router = useRouter()

const searchValue = ref('')
const historyStore = useHistoryStore()
const { historyList } = storeToRefs(historyStore)

const goSearch = (keyword: string) => {
  // 是否在历史列表中
  const index = historyStore.indexOfHistory(keyword)
  if (index !== -1) {
    // 有相同 删除
    historyStore.removeHistory(keyword)
  }
  // 没有相同 加到最前面
  historyStore.addHistory(keyword)
  // 跳转
  router.push({
    path: '/searchlist',
    query: {
      keyword
    }
  })
}
const clearHistory = () => {
  searchValue.value = ''
  historyStore.clearHistory()
}
</script>

<style scoped lang="scss">
.search {
  .van-search {
    padding: 10px 15px;
  }
  
  ::v-deep(.van-search__action) {
    background-color: #c21401;
    color: #fff;
  }
  .title {
    padding: 0 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 18px;
    color: #333;
    .van-icon {
      cursor: pointer;
    } 
  }
  .history-list {
    padding: 0 15px;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    gap: 5%;
    margin-top: 10px;
    .history-item {
      padding: 10px 0;
      font-size: 14px;
      text-align: center;
      color: #333;
      align-items: center;
      width: 30%;
      border: 1px solid #ccc;
      border-radius: 5px;
      padding: 5px 10px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-bottom: 10px;
      cursor: pointer;
    }
  }
}
</style>
  